package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DishServiceImpl implements DishService {


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getDishByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }









    /**
     * 根据套餐分类查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> dishList(Long categoryId) {
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);

        return dishMapper.getDishByCategoryId(dish);
    }

    /**
     * 修改菜品状态
     * @param id
     * @param status
     */
    @Override
    public void setStatus(Long id, Integer status) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);

        dishMapper.update(dish);

        if(status == StatusConstant.DISABLE){
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);

            List<Long> setMealIds = setmealDishMapper.getSetmealIdsByDishId(dishIds);
            if(!setMealIds.isEmpty()){

                for (Long setMealId : setMealIds) {
                        Setmeal setmeal = Setmeal.builder().id(setMealId).status(StatusConstant.DISABLE).build();
                        setmealMapper.update(setmeal);

                }

            }
        }
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 先修改菜品信息
        dishMapper.update(dish);


        // 先删除原有口味数据
        dishFlavorMapper.deleteByDishId(dish.getId());

        // 重新插入口味数据
        // 向口味表中插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {

            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });

            dishFlavorMapper.InsertFlavor(flavors);
        }
    }

    /**
     * 根据id查询菜品相关信息
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        Dish dish = dishMapper.getByIds(id);

        List<DishFlavor> dish_flavor = dishFlavorMapper.getByDishId(id);


        // 封装到vo
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dish_flavor);

        return dishVO;

    }





    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private com.sky.mapper.setmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 删除菜品
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {

        // 起售菜品不能被删除
        ids.forEach(dishId -> {
            Dish dish = dishMapper.getByIds(dishId);
            if(Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });


        // 被套餐关联菜品不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(ids);
        if(!setmealIds.isEmpty()) {
            // 当前菜品被关联了不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        // 删除菜品数据
        for (Long id : ids) {
            dishMapper.DeleteById(id);
            // 删除对应口味
            dishFlavorMapper.deleteByDishId(id);

        }

       // 批量删除
        // TODO 此处有BUG 前端删除报错 后端控制台正常显示sql语句 数据库未删除
//        dishMapper.deleteByIds(ids);
//        dishFlavorMapper.deleteByIds(ids);

    }





    /**
     * 菜品分页查询
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page =  dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }



    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void SaveDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);


        // 向菜品中插入一条数据
        dishMapper.Insert(dish);

        // 获取执行insert后的主键id
        Long dishId = dish.getId();

        // 向口味表中插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {

            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });

            dishFlavorMapper.InsertFlavor(flavors);
        }
    }
}
